package com.chookss.home.adapter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.document.DocumentBaseSecondActivity;
import com.chookss.home.document.DocumentDetailActivity;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.document.DownloadService;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.home.studyPlan.StudyPlanAddActivity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.BottomListsDialog;
import com.chookss.view.ForScreenInitDialog;
import com.chookss.view.SelectDialogListener;
import com.chookss.view.listener.ShareDialogListener;
import com.chookss.wxapi.ShareActivity;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.annotations.Nullable;

public class DocunmentListAdapter extends BaseQuickAdapter<DocunmentEntity, BaseViewHolderEx> {
    private Activity context;
    private ArrayList<Map<String, String>> directoryList = new ArrayList<>();
    private BottomListsDialog bottomListsDialog = null;
    private BottomListsDialog bottomListsFolderDialog = null;
    private List<String> dialogList = new ArrayList<>();
    private List<String> dialogFolderList = new ArrayList<>();
    private String tag;//记录来源
    private int level;//层级
    private int type;//0展示更多 1展示多少人阅读textview2发布图文过来的
    private boolean isTask = false;

    public DocunmentListAdapter(int layoutResId, Activity context, @Nullable List<DocunmentEntity> data, int level, int type, ArrayList<Map<String, String>> directoryList, String tag) {
        super(layoutResId, data);
        this.context = context;
        this.level = level;
        this.directoryList = directoryList;
        this.tag = tag;
        this.type = type;
        dialogList.add("分享");
        dialogList.add("在电脑上查看");
        dialogList.add("加入学习任务");
        dialogList.add("查看");
        dialogList.add("详细信息");
        dialogList.add("取消");
        dialogFolderList.add("查看");
        dialogFolderList.add("详细信息");
        dialogFolderList.add("取消");
    }

    private String key;

    public void searchNotifyDataSetChanged(String key) {
        this.key = key;
        notifyDataSetChanged();
    }

    @Override
    protected void convert(BaseViewHolderEx helper, DocunmentEntity entity) {
        ImageView ivIconType = helper.getView(R.id.ivIconType);
        LinearLayout llMidel = helper.getView(R.id.llMidel);
        TextView tvItemTitle = helper.getView(R.id.tvItemTitle);
        TextView tvItemDate = helper.getView(R.id.tvItemDate);
        TextView tvItemSize = helper.getView(R.id.tvItemSize);
        TextView tvPeople = helper.getView(R.id.tvPeople);
        ImageView ivMore = helper.getView(R.id.ivMore);
        RelativeLayout llMore = helper.getView(R.id.llMore);
        ProgressBar progressBar = helper.getView(R.id.progressBar);
        if (type == 1) {
            tvPeople.setVisibility(View.VISIBLE);
            ivMore.setVisibility(View.GONE);
            tvPeople.setText(Utils.changeCounts(entity.getReadNum()) + "人已读");
        } else {
            tvPeople.setVisibility(View.GONE);
            ivMore.setVisibility(View.VISIBLE);
        }
        if (entity.getProgress() == 0 || entity.getProgress() == 100) {
            progressBar.setVisibility(View.GONE);
        } else {
            progressBar.setVisibility(View.VISIBLE);
            progressBar.setProgress(entity.getProgress());
        }
        if (Utils.isNull(key)) {
            tvItemTitle.setText(entity.getDataTitle());
        } else {
            tvItemTitle.setText(Utils.matcherSearchTitle(context.getResources().getColor(R.color.main_color), entity.getDataTitle(), key));
        }

        if (!Utils.isNull(entity.getUploadTime())) {
            tvItemDate.setText(Utils.getAccurateDate(entity.getUploadTime()));
        } else {
            tvItemDate.setText(Utils.getAccurateDate(entity.getCreateTime()));
        }


        String dataType = entity.getDataType();//0 --文件夹 1--文件
        String fileType = entity.getFileType();//文件类型1--word 2 --excel 3--PPT  4pdf
        if ("1".equals(dataType)) {
            if ("1".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_w).into(ivIconType);
            } else if ("2".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_x).into(ivIconType);
            } else if ("3".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_p).into(ivIconType);
            } else if ("4".equals(fileType)) {
                Glide.with(context).load(R.drawable.icon_pdf).into(ivIconType);
            } else {
                Glide.with(context).load(R.drawable.icon_file_default).into(ivIconType);
            }
            tvItemSize.setText(Utils.changeKM(entity.getDataSize()));
        } else {
            Glide.with(context).load(R.drawable.icon_folder_big).into(ivIconType);
            tvItemSize.setText("");
        }
        llMidel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Urls.antiShake.check()) {
                    return;
                }
                if (type == 2) {
                    //图文发布过来的，要回传回去，不是打开
                    Intent intent = new Intent();
                    intent.putExtra("size", tvItemSize.getText().toString());
                    intent.putExtra("name", entity.getDataTitle());
                    intent.putExtra("wordType", entity.getFileType());
                    intent.putExtra("dataCode", entity.getDataCode());
                    intent.putExtra("isShare", entity.getShareFlag());
                    context.setResult(1003, intent);
                    EventBus.getDefault().post(new MyEvent("TuwenSearchWord_Finish"));
                } else {
                    lookDocunment(entity, tvItemTitle.getText().toString(), helper.getItemPosition());
                }

            }
        });
        llMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(dataType)) {
                    bottomListsDialog = new BottomListsDialog(context, dialogList, new SelectDialogListener() {
                        @Override
                        public void onCancel() {

                        }

                        @Override
                        public void onListItemClick(int position, List<String> list) {
                            if (position == 0) {
                                Intent intent = new Intent(context, ShareActivity.class);
                                intent.putExtra("title", entity.getDataTitle());
                                intent.putExtra("createEmployeeName", entity.getUploadPersonName());
                                intent.putExtra("content", entity.getKeyWord());
                                intent.putExtra("resourceId", entity.getDataCode());
                                intent.putExtra("size", tvItemSize.getText().toString());
                                intent.putExtra("resourceType", 1);
                                context.startActivity(intent);
                            } else if (position == 1) {
                                new ForScreenInitDialog(context, new ShareDialogListener() {
                                    @Override
                                    public void onClick() {
                                        saveScan(entity.getDataCode());
                                    }
                                }).show();
                            } else if (position == 2) {
                                Intent intent = new Intent(context, StudyPlanAddActivity.class);
                                intent.putExtra("resourceId", entity.getDataCode());
                                intent.putExtra("describe", entity.getKeyWord());
                                intent.putExtra("resourceType", 5);
                                intent.putExtra("title", entity.getDataTitle());
                                intent.putExtra("content", entity.getKeyWord());
                                intent.putExtra("size", tvItemSize.getText().toString());
                                context.startActivity(intent);
                            } else if (position == 3) {
                                lookDocunment(entity, tvItemTitle.getText().toString(), helper.getItemPosition());
                            } else if (position == 4) {
                                //详细信息
                                Intent intent = new Intent(context, DocumentDetailActivity.class);
                                intent.putExtra("dataCode", entity.getDataCode());
                                context.startActivity(intent);

                            }
                            bottomListsDialog.dismiss();
                        }
                    });
                    bottomListsDialog.show();
                } else {
                    bottomListsFolderDialog = new BottomListsDialog(context, dialogFolderList, new SelectDialogListener() {
                        @Override
                        public void onCancel() {

                        }

                        @Override
                        public void onListItemClick(int position, List<String> list) {
                            if (position == 0) {
                                lookDocunment(entity, tvItemTitle.getText().toString(), helper.getItemPosition());
                            } else if (position == 1) {
                                //详细信息
                                Intent intent = new Intent(context, DocumentDetailActivity.class);
                                intent.putExtra("dataCode", entity.getDataCode());
                                context.startActivity(intent);
                            }
                            bottomListsFolderDialog.dismiss();
                        }
                    });
                    bottomListsFolderDialog.show();
                }
            }
        });
    }

    public void setTask() {
        this.isTask = true;
    }

    private void lookDocunment(DocunmentEntity entity, String title, int position) {
        //查看
        if ("0".equals(entity.getDataType())) {
            Intent intent = new Intent(context, DocumentBaseSecondActivity.class);
            Bundle bundle = new Bundle();
            //须定义一个list用于在budnle中传递需要传递的ArrayList<Object>,这个是必须要的
            ArrayList bundlelist = new ArrayList();
            bundlelist.add(directoryList);
            bundle.putParcelableArrayList("list", bundlelist);
            bundle.putString("parantCode", entity.getDataCode());
            bundle.putString("title", entity.getDataTitle());
            intent.putExtras(bundle);
            intent.putExtra("level", level + 1);
            context.startActivity(intent);
        } else if ("1".equals(entity.getDataType())) {
            requestSTORAGE(entity, title, position);
        }
    }

    private void requestSTORAGE(DocunmentEntity entity, String retitle, int rePosition) {
        XXPermissions.with(context)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            getDocunmentDetail(entity, retitle, rePosition);
                        } else {
                            MyToast.show("存储未被授权，请先去权限设置里面授权");
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(context, denied, quick);
                    }
                });
    }

    private void getDocunmentDetail(DocunmentEntity entity, String docTitle, int docPosition) {
        Map<String, String> map = new HashMap<>();
        map.put("dataCode", entity.getDataCode());
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<DocunmentEntity>>() {
        }.getType(), null, Urls.getDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<DocunmentEntity>() {
            @Override
            public void onSuccess(DocunmentEntity newData) {
                if (newData != null) {
                    openFile(newData, docTitle, docPosition,entity.isError());
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void saveScan(String code) {
        Map<String, String> map = new HashMap<>();
        map.put("resourceId", code);
        map.put("resourceType", "1");
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.saveScan, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                JSONObject reObject = null;
                try {
                    reObject = new JSONObject(data);
                    if ("200".equals(reObject.getString("code"))) {
                    } else {
                        MyToast.show(reObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(errorMsg);
            }
        });
    }

    private void openFile(DocunmentEntity entity, String title, int position,boolean isError) {
        if (!Utils.isNull(entity.getDataUrl())) {
            String url, name, fileUrl, urls;
            url = entity.getDataUrl();
            urls = url.split("\\?")[0];
            fileUrl = urls.substring(urls.lastIndexOf("/") + 1, urls.length());
            if (MyApp.downloadFiles.contains(title)||!MyApp.mIsInitTBSSuccess||isError) {
                if (!MyApp.docunmentOpen) {
                    Intent intent = new Intent(context, DocumentPreviewActivity.class);
                    intent.putExtra("fileUrl", fileUrl);
                    intent.putExtra("fileName", title);
                    intent.putExtra("dataCode", entity.getDataCode());
                    if (isTask) {
                        intent.putExtra("type", 1);
                    }
                    context.startActivity(intent);
                }
            } else {
                entity.setProgress(1);
                notifyItemChanged(position);
                Intent intent = new Intent(context, DownloadService.class);
                intent.putExtra("fileUrl", fileUrl);
                intent.putExtra("fileName", title);
                intent.putExtra("url", url);
                intent.putExtra("dataCode", entity.getDataCode());
                intent.putExtra("position", position);
                intent.putExtra("tag", tag);
                context.startService(intent);
            }

        }
    }


}
